package com.alibaba.datax.core.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CleanUtils {
	
	private static final int SIZE = 6;
	private static final String SYMBOL = "*";
	
	/**
	 * 通用脱敏
	 */
	public static String toClearing(Object valueOf) {
		if (null == valueOf || "".equals(valueOf)) {
			return (String) valueOf;
		}
		String value = valueOf.toString();
		int len = value.length();
		int pamaone = len / 2;
		int pamatwo = pamaone - 1;
		int pamathree = len % 2;
		StringBuilder stringBuilder = new StringBuilder();
		if (len <= 2) {
			if (pamathree == 1) {
				return SYMBOL;
			}
			stringBuilder.append(SYMBOL);
			stringBuilder.append(value.charAt(len - 1));
		} else {
			if (pamatwo <= 0) {
				stringBuilder.append(value.substring(0, 1));
				stringBuilder.append(SYMBOL);
				stringBuilder.append(value.substring(len - 1, len));

			} else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) {
				int pamafive = (len - SIZE) / 2;
				stringBuilder.append(value.substring(0, pamafive));
				for (int i = 0; i < SIZE; i++) {
					stringBuilder.append(SYMBOL);
				}
				if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0)) {
					stringBuilder.append(value.substring(len - pamafive, len));
				} else {
					stringBuilder.append(value.substring(len - (pamafive + 1), len));
				}
			} else {
				int pamafour = len - 2;
				stringBuilder.append(value.substring(0, 1));
				for (int i = 0; i < pamafour; i++) {
					stringBuilder.append(SYMBOL);
				}
				stringBuilder.append(value.substring(len - 1, len));
			}
		}
		return stringBuilder.toString();

	}


	/**
	 * 验证是否需要清洗
	 */
	public static boolean ifValid(Object phone) {
		if(phone == null) {
			return false;
		}
		String phoneStr=phone.toString();
		String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
		if (phoneStr.length() != 11) {
			return false;
		}
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(phoneStr);
		boolean isMatch = m.matches();
		return isMatch;
	}
}
